// #region 环境变量
import dotenv from "dotenv";
const { NODE_ENV } = process.env;
dotenv.config({ path: `.env.${NODE_ENV}` });

//#endregion
// import createError from "http-errors";
import path from "path";
// import cookieParser from 'cookie-parser';
import logConfig from "./src/middleware/log"; // 日志中间件
import { JWT_KEY, unlessPath } from "./src/config/code";
import { Request, Response } from "express";
// 生产环境中间件
import productionMiddleware from "./src/middleware/prodution";
import { responseError } from "./src/common/response";

// #region 路由
import usersRouter from "./src/routes/user/index";
import roleRouter from "./src/routes/role/index";
// #endregion
import express from "express";
import { expressjwt } from "express-jwt";
const app = express();

// 生产环境中间件
if (NODE_ENV === "production") {
  productionMiddleware(app);
}

// 日志配置
app.use(logConfig);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.resolve(__dirname, "public"))); // 静态资源
app.use(
  expressjwt({
    secret: JWT_KEY,
    algorithms: ["HS256"],
  }).unless({
    path: unlessPath,
  })
); //jwt

app.use("/user", usersRouter);
app.use("/role", roleRouter);

// catch 404 and forward to error handler
app.use(function (req, res) {
  res.json(responseError("请求的路径不存在"));
  // console.log("404");
  //   next(createError(404));
});

// error handler
app.use(function (err: any, req: Request, res: Response) {
  if (err.name === "UnauthorizedError") {
    res.json(responseError("用户验证失败，请重新登录"));
  }
  console.log(err);
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  //  res.render("error");
});

export default app;
